<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box{
            border: 3px dashed #ccc;
            padding: 20px;
        }
    </style>
    <script src="../assets/js/vue.js"></script>
</head>
<body>
    <div id="app" class="box">
        <p>父组件</p>
        <comp-b></comp-b>
        <br>
        <comp-a></comp-a>
    </div>

    <script type="text/x-template" id="CompA">
        <div class="box">
            <p>子组件A</p>
            <p>tempInfo:{{ tempInfo }}</p>
        </div>
    </script>

    <script type="text/x-template" id="CompB">
        <div class="box">
            <p>子组件B</p>
            <p>info:{{ info }}</p>
            <input type="text" v-model="info">
        </div>
    </script>

    <script>
        Vue.component("CompA",{
            template:"#CompA",
            data() {
                return {
                    tempInfo:""
                }
            },
            methods: {
                bindInfoEvent(){
                    if(!this.$root._events.updateInfo){
                        this.$root.$on("updateInfo",(nv)=>{
                            console.log("CompA-bindInfoEvent-updateInfo事件:",nv)
                            this.tempInfo = nv;
                        })
                    }
                    console.log(this.$root._events);
                }
            },
            // created() {
            //     this.bindInfoEvent()
            // },
            beforeMount() {
                this.bindInfoEvent()
            },
            // mounted() {
            //     this.bindInfoEvent()
            // },
        })

        Vue.component("CompB",{
            template:"#CompB",
            data() {
                return {
                    info:"CompB-info数据"
                }
            },
            watch:{
                info(){
                    this.emitInfoEvent()
                }
            },
            methods:{
                emitInfoEvent(){
                    console.log(this.$root)
                    this.$root.$emit("updateInfo",this.info)
                }
            },
            // created(){
            //     this.emitInfoEvent()
            // }
            mounted() {
                this.emitInfoEvent()
            },
        })

        new Vue({
            el:"#app"
        })
    </script>
</body>
</html>